package com.sakura.util.thread.threadPool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by apple on 2018/7/26.
 */
public class BatchProcessor<T> implements BatchProcess<T> {
    private static final int MAX_POOL_SIZE = 3;
    private static final int KEEP_ALIVE_TIME = 1;
    private final ExecutorService service;

    public BatchProcessor(final int corePoolSize) {
        this.service = new ThreadPoolExecutor(corePoolSize, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(corePoolSize));
    }

    @Override
    public List<Future<T>> process(List<T> list) {
        List<Future<T>> futures = new ArrayList<>();
        for(T task : list){
            futures.add(service.submit(new TaskExecutor(task)));
        }
        service.shutdown();
        System.out.println("shutdown");
        return futures;
    }

    private class TaskExecutor implements Callable<T> {
        private T t;

        public TaskExecutor(T t){
            this.t = t;
        }
        @Override
        public T call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for(int i=0;i<100;i++)
                sum += i;
            System.out.println("子线程结束计算");

            System.out.println("打出来秋秋："+t);
            return t;
        }
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("习","国","定","习2","国2","定2");
        BatchProcess<String> batchProcess = new BatchProcessor(3);
        batchProcess.process(list);
    }
}
